package ay.shadow.seckill.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import ay.shadow.seckill.config.AccessLimit;
import ay.shadow.seckill.excepetion.GlobalException;
import ay.shadow.seckill.entity.Order;
import ay.shadow.seckill.entity.SeckillMessage;
import ay.shadow.seckill.entity.SeckillOrder;
import ay.shadow.seckill.entity.User;
import ay.shadow.seckill.rabbitmq.MQSender;
import ay.shadow.seckill.service.IGoodsService;
import ay.shadow.seckill.service.IOrderService;
import ay.shadow.seckill.service.ISeckillOrderService;
import ay.shadow.core.utils.JsonUtils;
import ay.shadow.seckill.entity.vo.GoodsVo;
import ay.shadow.seckill.entity.vo.RespBean;
import ay.shadow.seckill.entity.vo.RespBeanEnum;
import com.wf.captcha.ArithmeticCaptcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/seckill")
@Slf4j
public class SeckillController implements InitializingBean {

    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private ISeckillOrderService seckillOrderService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MQSender mqSender;
    private Map<Long, Boolean> EmptyStockMap = new HashMap<>();
    @Autowired
    private RedisScript<Long> script;

    /**
     * @Param 获取秒杀方法
     * @Description 返回orderId表示成功，-1：失败；0：排队中
     * @Return orderId
     */
    @RequestMapping(value = "/getResult", method = RequestMethod.GET)
    @ResponseBody
    public RespBean getResult(User user, Long goodsId) {
        if (user == null) {
            return RespBean.error(RespBeanEnum.SESSION_ERROR);
        }
        log.info("getResult error:{}", goodsId);
        Long orderId = seckillOrderService.getResult(user, goodsId);
        log.info("getResult error:{}", orderId);
        return RespBean.success(orderId);
    }


    /**
     * @Param
     * @Description 秒杀功能
     * @Return
     */
    @RequestMapping("/doSeckill2")
    public String doSecKill2(Model model, User user, Long goodsId) {
        if (user == null) {
            return "login";
        }
        model.addAttribute("user", user);
        GoodsVo goods = goodsService.findGoodsVoByGoodsId(goodsId);
        // 判断库存
        if (goods.getStockCount() < 1) {
            model.addAttribute("errMsg", RespBeanEnum.EMPTY_STOCK);
            return "secKillFail";
        }
        // 判断是否重复抢购
        SeckillOrder seckillOrder = seckillOrderService.getOne(new QueryWrapper<SeckillOrder>().eq("user_id", user.getId()).eq("goods_id", goodsId));
        if (seckillOrder != null) {
            model.addAttribute("errmsg", RespBeanEnum.REPEAT_ERROR);
            return "secKillFail";
        }
        Order order = orderService.seckill(user, goods);
        model.addAttribute("order", order);
        model.addAttribute("goods", goods);
        return "orderDetail";

    }


    /**
     * @Param
     * @Description 秒杀功能
     * @Return
     */
    @RequestMapping(value = "/{path}/doSeckill", method = RequestMethod.POST)
    @ResponseBody
    public RespBean doSecKill(@PathVariable String path, User user, Long goodsId) {
        if (user == null) {
            return RespBean.error(RespBeanEnum.SESSION_ERROR);
        }
        // redis预减库存
        ValueOperations valueOperations = redisTemplate.opsForValue();
        boolean check = orderService.checkPath(user, goodsId, path);
        if (!check) {
            return RespBean.error(RespBeanEnum.QUEST_ILLEGAL);
        }
        // 判断是否重复抢购
        SeckillOrder seckillOrder =
                (SeckillOrder) redisTemplate.opsForValue().get("order:" + user.getId() + ":" + goodsId);
        if (seckillOrder != null) {
            //model.addAttribute("errmsg",RespBeanEnum.REPEAT_ERROR);
            //return "secKillFail";
            return RespBean.error(RespBeanEnum.REPEAT_ERROR);
        }
        // 内存标记，减少redis的访问
        if (EmptyStockMap.get(goodsId)) {
            log.info("EmptyStockMap error");
            return RespBean.error(RespBeanEnum.EMPTY_STOCK);
        }

        // 预减库存
        //Long stock = valueOperations.decrement("seckillGoods:" + goodsId);
        Long stock = (Long) redisTemplate.execute(script, Collections.singletonList("seckillGoods:" + goodsId), Collections.EMPTY_LIST);
        log.info(stock.toString());
        if (stock < 0) {
            // 判断库存是否为0
            EmptyStockMap.put(goodsId, true);
            log.info("预减库存错误");
            valueOperations.increment("seckillGoods" + goodsId);
            return RespBean.error(RespBeanEnum.EMPTY_STOCK);
        }
        // 下单
        SeckillMessage seckillMessage = new SeckillMessage(user, goodsId);
        mqSender.sendSeckillMessage(JsonUtils.object2JsonStr(seckillMessage));
        return RespBean.success(0);

        /*
        // 判断库存
        if (goods.getStockCount()<1){
            //model.addAttribute("errMsg", RespBeanEnum.EMPTY_STOCK);
            return RespBean.error(RespBeanEnum.EMPTY_STOCK);
            //return "secKillFail";
        }
        // 判断是否重复抢购
        //SeckillOrder seckillOrder = seckillOrderService.getOne(new QueryWrapper<SeckillOrder>().eq("user_id", user.getId()).eq("goods_id", goodsId));
        SeckillOrder seckillOrder =
                (SeckillOrder) redisTemplate.opsForValue().get("order:" + user.getId() + ":" + goods.getId());
        if (seckillOrder != null){
            //model.addAttribute("errmsg",RespBeanEnum.REPEAT_ERROR);
            //return "secKillFail";
            return RespBean.error(RespBeanEnum.REPEAT_ERROR);
        }
        Order order = orderService.seckill(user,goods);
        //model.addAttribute("order",order);
        //model.addAttribute("goods",goods);
        //return "orderDetail";
        return RespBean.success(order);
        */
    }

    @RequestMapping(value = "/captcha", method = RequestMethod.GET)
    public void verifyCode(User user, Long goodsId, HttpServletResponse response) {
        if (user == null || goodsId < 0) {
            throw new GlobalException(RespBeanEnum.QUEST_ILLEGAL);
        }
        log.info("captcha,User:{}", user.toString());
        //设置请求头为输出图片的类型
        response.setContentType("image/jpg");
        response.setHeader("Pargam", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        //生成验证码
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(130, 32, 3);
        redisTemplate.opsForValue().set("captcha:" + user.getId() + ":" + goodsId, captcha.text(), 300, TimeUnit.SECONDS);
        try {
            captcha.out(response.getOutputStream());
        } catch (IOException e) {
            log.error("验证码生成失败", e.getMessage());
        }
    }


    /**
     * @Param
     * @Description 接口隐藏，获取秒杀地址
     * @Return
     */
    @AccessLimit(second=5,maxCount=5,needLogin=true)
    @RequestMapping(value = "/path", method = RequestMethod.GET)
    @ResponseBody
    public RespBean getSeckillPath(User user, Long goodsId, String captcha, HttpServletRequest request) {
        if (user == null) {
            log.info("user is null");
            return RespBean.error(RespBeanEnum.SESSION_ERROR);
        }
        //ValueOperations valueOperations = redisTemplate.opsForValue();
        //String uri = request.getRequestURI();
        //captcha = "0";
        //Integer count = (Integer) valueOperations.get(uri + ":" + user.getId());
        //if (count == null) {
        //    valueOperations.set(uri + ":" + user.getId(), 1, 5, TimeUnit.SECONDS);
        //} else if (count < 5) {
        //    log.info("count<5:{}",count);
        //    valueOperations.increment(uri+":" + user.getId());
        //} else {
        //    log.info("count>5:{}",count);
        //    return RespBean.error(RespBeanEnum.ACCESS_LIMIT_REACHED);
        //}
        boolean check = orderService.checkCaptcha(user, goodsId, captcha);
        if (!check) {
            return RespBean.error(RespBeanEnum.ERROR_CAPTCHA);
        }
        log.info("user:{}", user.toString());
        String str = orderService.createPath(user, goodsId);
        return RespBean.success(str);
    }


    /**
     * @Param
     * @Description 系统初始化，商品库存数量加载到redis里去
     * @Return Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        List<GoodsVo> list = goodsService.findGoodsVo();
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        list.forEach(goodsVo -> {
            redisTemplate.opsForValue().
                    set("seckillGoods:" + goodsVo.getId(), goodsVo.getStockCount());
            EmptyStockMap.put(goodsVo.getId(), false);
        });
    }
}
